package controller

import (
	"gitee.com/song-yao-shun/MQH/dto"
	"gitee.com/song-yao-shun/MQH/model"
	"gitee.com/song-yao-shun/MQH/response"
	"gitee.com/song-yao-shun/MQH/respository"
	"gitee.com/song-yao-shun/MQH/vo"
	"github.com/gin-gonic/gin"
	"strconv"
)

type IFctController interface {
	RestController
}

type FctController struct {
	FctRty respository.FctRepository
}

func (f FctController) Create(ctx *gin.Context) {
	// 接收参数
	var requestFct vo.CreateFctRequest
	if err := ctx.ShouldBind(&requestFct); err != nil {
		response.Fail(ctx, nil, "数据验证错误！")
		return
	}

	// 创建 page
	fct := model.Fct{
		PageId: 	requestFct.PageId,
		Name: 		requestFct.Name,
		Type: 		requestFct.Type,
		Desc: 		requestFct.Desc,
	}

	fctId, err := f.FctRty.Create(fct)
	if err != nil {
		response.Fail(ctx, nil, "新建失败！")
		return
	}

	// 返回
	response.Success(ctx, gin.H{"data":fctId}, "新建成功！")
}
func (f FctController) Update(ctx *gin.Context) {
	// 接收参数
	var requestFct vo.CreateFctRequest
	if err := ctx.ShouldBind(&requestFct); err != nil {
		response.Fail(ctx, nil, "数据验证错误，请检查提交的内容！")
		return
	}

	// 获取 path 中的参数
	fctId, _ := strconv.Atoi(ctx.Params.ByName("id"))
	updateFct, err := f.FctRty.SelectById(fctId)
	if err != nil {
		response.Fail(ctx, nil, "功能不存在！")
		return
	}

	// 判断 pageid 是否有效
	if updateFct.PageId != requestFct.PageId{
		p := respository.NewPageRepository()
		_, err := p.SelectById(requestFct.PageId)
		if err != nil {
			response.Fail(ctx, nil, "修改后的页面不存在！")
			return
		}
	}

	// 更新 struct
	updateFct.PageId 	= requestFct.PageId
	updateFct.Name 		= requestFct.Name
	updateFct.Type 		= requestFct.Type
	updateFct.Desc 		= requestFct.Desc

	fct, err := f.FctRty.Update(*updateFct)
	if err != nil {
		panic(err)
	}

	response.Success(ctx, gin.H{"data":fct}, "修改成功。")
}

func (f FctController) Show(ctx *gin.Context) {

	// 获取 path 中的参数
	fctId, _ := strconv.Atoi(ctx.Params.ByName("id"))
	fct := f.FctRty.SelectFullFctById(fctId)
	if fct.ID != fctId {
		response.Fail(ctx, nil, "功能不存在！")
		return
	}

	response.Success(ctx, gin.H{"data":fct}, "")
}

func (f FctController) Delete(ctx *gin.Context) {

	// 获取 path 中的参数
	fctId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	if rowsAffected := f.FctRty.DeleteById(fctId);rowsAffected != 1 {
		response.Fail(ctx, nil, "删除失败，请重试！")
		return
	}

	response.Success(ctx, nil, "删除成功！")
}

func (f FctController) List(ctx *gin.Context) {

	// 接收参数
	var fctList vo.FuncList
	if err := ctx.ShouldBind(&fctList); err != nil {
		response.Fail(ctx, nil, "数据验证错误，请检查提交的内容！")
		return
	}

	fullFcts, total := f.FctRty.List(fctList)

	if fctList.SelectType != ""{
		response.Success(ctx, gin.H{"data":dto.ToFctDto(fullFcts), "total":total}, "查询列表成功。")
		return
	}

	response.Success(ctx, gin.H{"data":fullFcts, "total":total}, "查询列表成功。")
}

func NewFctController() IFctController{
	return FctController{FctRty: respository.NewFctRepository()}
}

